package com.srwl.mytx.contrack;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.alipay.sdk.app.AuthTask;
import com.srwl.mytx.Constant;
import com.srwl.mytx.MLOC;
import com.srwl.mytx.MyApplication;
import com.srwl.mytx.converter.MyRequestBodyConverter;
import com.srwl.mytx.domain.AliOssService;
import com.srwl.mytx.greendao.ContactDao;
import com.srwl.mytx.domain.Contact;
import com.srwl.mytx.domain.User;
import com.srwl.mytx.Helper;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.dao.DBManager;
import com.srwl.mytx.domain.AuthResult;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AliService;
import com.srwl.mytx.service.UserService;
import com.srwl.mytx.utils.PreferenceManager;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by dahai2070 on 2018/2/27 0027.
 */

public class LoginPresenterImpl implements LoginConstrack.Presenter {
    private static final String TAG = "LoginPresenterImpl";
    private LoginConstrack.View view;
    private Context context;
    private int passwordErrorCount;
    private static final int SDK_AUTH_FLAG = 2;
    private int loginToAliTryCount = 0;

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_AUTH_FLAG: {
                    @SuppressWarnings("unchecked")
                    AuthResult authResult = new AuthResult((Map<String, String>) msg.obj, true);
                    String resultStatus = authResult.getResultStatus();

                    // 判断resultStatus 为“9000”且result_code
                    // 为“200”则代表授权成功，具体状态码代表含义可参考授权接口文档
                    if (TextUtils.equals(resultStatus, "4000") && TextUtils.equals(authResult.getResultCode(), "1005")) {
                        // 其他状态值则为授权失败
                        Toast.makeText(context,
                                "支付宝账户已经冻结", Toast.LENGTH_SHORT).show();
                        view.setLoginButtonStatus(true);
                        return;
                    }
                    if (TextUtils.equals(resultStatus, "4000") && TextUtils.equals(authResult.getResultCode(), "202")) {
                        Toast.makeText(context,
                                "系统异常", Toast.LENGTH_SHORT).show();
                        view.setLoginButtonStatus(true);
                        return;
                    }
                    if (TextUtils.equals(resultStatus, "6001")) {
                        Log.i(TAG, "handleMessage: 用户取消了授权登录操作");
                        view.setLoginButtonStatus(true);
                        return;
                    }
                    if (TextUtils.equals(resultStatus, "6002")) {
                        Toast.makeText(context,
                                "网络连接出错", Toast.LENGTH_SHORT).show();
                        view.setLoginButtonStatus(true);
                        return;
                    }
                    // 获取alipay_open_id，调支付时作为参数extern_token 的value
                    // 传入，则支付账户为该授权账户
                    view.showProgressDialog("登录中...");
                    Log.i(TAG, "支付宝登录授权成功:" + authResult.getAuthCode());
                    //封装authCodce参数
                    String authCode = authResult.getAuthCode();
                    Map<String, String> mapInfo = new HashMap<>();
                    mapInfo.put("auth_code", authCode);
                    //如果授权成功,那么调用服务器端授权登录接口完成支付宝授权登录操作
                    UserProfileManager.getInstance().setUserToken("");
                    //如果授权成功,那么调用服务器端授权登录接口完成支付宝授权登录操作
                    aliAuthLogin(mapInfo);
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    public LoginPresenterImpl(LoginConstrack.View view, Context context) {
        this.view = view;
        this.context = context;
    }

    @Override
    public void start() {

    }


    @Override
    public void login(final User loginUser) {
        if (!Utils.isNetworkConnected(context)) {
            Toast.makeText(context, context.getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
            return;
        }
//        JSONObject encrypt = new JSONObject();
//        try {
//            String serviceRsaPublicKey = context.getString(R.string.service_public_key);
//            encrypt = HttpEncryptUtil.appEncrypt(user, serviceRsaPublicKey);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        Log.d(TAG, "加密后内容：" + encrypt);
        final JSONObject body = new JSONObject();
        body.put("ct", loginUser);
        view.setLoginButtonStatus(false);
        view.showProgressDialog(context.getString(R.string.logining));
        RetrofitManager
                .getInstance()
                .createRequest(UserService.class)
                .login(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(final Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            view.disMissProgressDialog();
                            view.setLoginButtonStatus(true);
                            Log.e(TAG, response.code() + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            return;
                        }
                        //登录失败
                        if (result.isError()) {
                            view.disMissProgressDialog();
                            view.setLoginButtonStatus(true);
                            Log.e(TAG, "login:" + result.getStatus() + result.getMsg());
                            switch (result.getStatus()) {
                                case Constant.LOGIN_ERROR_LIMIT:

                                    Integer expireMinutes = (Integer) result.getData();//单位分钟
                                    // view.showToast(expire(expireMinutes));
                                    final ConfirmDialog dialog = new ConfirmDialog(context, "限制登录", expire(expireMinutes));
                                    dialog.show();
                                    view.showRetrievePassWord();
                                    break;
                                case Constant.PASS_WORD_WRONG:
                                    if (passwordErrorCount >= 1) {//现在设置为当连续两次密码错误的额时候，显示找回密码，因为找回密码会耗费短信，多少次错误才显示找回密码，以后实践中再根据情况决定
                                        view.showRetrievePassWord();
                                    }
                                    passwordErrorCount++;
                                    if (result.getData() != null) {
                                        Integer remainLoginTime = (Integer) result.getData();
                                        view.showPasswordError();
                                        if (remainLoginTime > 3) {

                                            view.showToast(context.getString(R.string.pass_word_wrong));
                                        } else if (remainLoginTime != 0) {
                                            final ConfirmDialog dialog_1 = new ConfirmDialog(context, "密码错误", "还可以尝试登录" + remainLoginTime + "次,超过次数限制账户将进入锁定状态。");
                                            dialog_1.show();
                                            view.showRetrievePassWord();
                                        } else {
                                            final ConfirmDialog dialog_1 = new ConfirmDialog(context, "密码错误", "再次输入错误密码账户将进入锁定状态，可通过手机号重置密码立即登录");
                                            dialog_1.show();
                                            view.showRetrievePassWord();
                                        }

                                    }
                                    break;
                                case Constant.USER_NAME_INVALID:
                                    view.showToast(context.getString(R.string.user_invalid));
                                    break;

                                default:
                                    view.showToast(context.getString(R.string.system_busy));
                            }
                            return;
                        }
                        // view.showToast(context.getString(R.string.login_success));
                        //获取返回的用户数据
                        analysisResult(result, loginUser);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        view.showToast(context.getString(R.string.system_busy));
                        view.setLoginButtonStatus(true);
                    }
                });
    }

    private void analysisResult(CommonResult result, User loginUser) {
        //关闭所有页面
        //  MyApplication.getInstance().finishActivities();
        //调用一次 登出，是为了当临时用户跳转到登录页面，并登录成功后，清除临时用户的数据
        if (result.getData() == null) {
            view.disMissProgressDialog();
            view.setLoginButtonStatus(true);
            return;
        }
        Helper.getInstance().reset();
        JSONObject data = (JSONObject) result.getData();
        if (data.containsKey("serviceTime")) {
            MyApplication.timeOffset = data.getLong("serviceTime") - System.currentTimeMillis();
        }
        Log.d(TAG, data.toString());
        //  Helper.getInstance().getVersionInfo();
        final User user = data.getObject("userInfo", User.class);
//        User userInof =  Helper.getInstance().getUserProfileManager().getLoginUserInfo();
        //授权登录回来,判断回传了用户的手机号,如果没有手机号,则清除之前上次用户登录的手机号
        if (TextUtils.isEmpty(user.getPhone())) {
            UserProfileManager.getInstance().setUserPhoneNumber("");
        }
        if (TextUtils.isEmpty(user.getAliAccount())) {
            UserProfileManager.getInstance().setLoginUserAliAccount("");
        }
        //登录回来,判断回传的用户的gender是否为空,如何为空,将性别设置为男
//        if (user.getGender() == null) {
//            UserProfileManager.getInstance().setUserGender(0);
//        }
        Log.i(TAG, "userInfo: " + user);
        //清空缓存中的用户数据
        //  Helper.getInstance().removeLoginUserInfo();
        //在这里判断的，避免上个登录用户的该条数据并未正常清理
        if (user.getLiveRoomSupperManager() == null) {
            PreferenceManager.getInstance().setLiveRoomSupperManager(false);
        }
        //保存登录用户个人信息
        UserProfileManager.getInstance().syncLoginUserInfo(user);

        ContactDao contactDao = DBManager.getInstance().getDaoSession().getContactDao();
        contactDao.deleteAll();//保存之前，清空所有联系人，这样保证数据与服务端同步
        //第一次阿里授权登录的时候，按注册逻辑处理，回传一个 系统联系人
        Contact tempContact = data.getObject("contact", Contact.class);
        if (tempContact != null) {
            contactDao.insertOrReplace(tempContact);
            DBManager.getInstance().getDaoSession().getUserDao().insertOrReplaceInTx(tempContact.getUser());
        }
        List<Contact> contacts = JSONObject.parseArray(data.getString("contacts"), Contact.class);
        if (contacts != null && contacts.size() != 0) {
            List<User> users = new ArrayList<>();
            // List<InfiniteConnect>infiniteConnects=new ArrayList<>();
            for (Contact contact : contacts) {
                if (contact.getType()==null) {
                    contact.setType(Constant.CONTACT_TYPE_NORMAL);
                }
                contact.settId(contact.getUser().getuId());
                users.add(contact.getUser());
//                                for (InfiniteConnect infiniteConnect : contact.getInfinite()) {
//                                    infiniteConnect.setcId(contact.getcId());
//                                }
//                                infiniteConnects.addAll(contact.getInfinite());
            }

            contactDao.insertInTx(contacts);
            DBManager.getInstance().getDaoSession().getUserDao().insertOrReplaceInTx(users);
            // DBManager.getInstance().getDaoSession().getInfiniteConnectDao().insertOrReplaceInTx(infiniteConnects);
        }
        //后端回传的视频和图片地址
        if (data.containsKey("topic_video_pre")) {
            AliOssService.TOPIC_VIDEO_PRE_URL = data.getString("topic_video_pre");
        }
        if (data.containsKey("topic_image_pre")) {
            AliOssService.TOPIC_IMAGE_PRE_URL = data.getString("topic_image_pre");
        }
        if (data.containsKey("live_host")) {
            MLOC.resetLiveHost(data.getString("live_host"));
        }
        view.showLoginSuccess();
    }

    /**
     * 获取支付宝授权链接
     */
    @Override
    public void alipayAuthUrl() {
        final JSONObject body = new JSONObject();
        view.setLoginButtonStatus(false);
//        view.showProgressDialog("去支付宝授权");
        //调用远程服务器接口生成授权链接
        RetrofitManager
                .getInstance()
                .createRequest(AliService.class)
                .getAuthUrl(body)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        //获取服务器端返回的结果
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            view.disMissProgressDialog();
                            view.setLoginButtonStatus(true);
                            Log.e(TAG, "授权链接错误" + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "获取授权链接出错 " + result.getMsg());
                            return;
                        }

                        //获取成功生成的授权码
                        String aliPayAuthUrl = (String) result.getData();
                        Log.d(TAG, "支付宝登录授权链接:" + aliPayAuthUrl);
                        //异步调用支付宝授权接口\
                        final String finaAliPayAuthUrl = aliPayAuthUrl;
                        Runnable runnable = new Runnable() {
                            @Override
                            public void run() {
                                //创建AuthTask对象
                                AuthTask authTask = new AuthTask((Activity) context);
                                //调用支付宝授权接口
                                Map<String, String> responseResult = authTask.authV2(finaAliPayAuthUrl, true);
                                AuthResult authResult = new AuthResult(responseResult, true);
                                //获取响应状态吗
                                String resultStatus = responseResult.get("resultStatus");
                                Log.i(TAG, "run: 支付宝响应状态码:" + resultStatus);
                                //获取响应的数据
                                String result = responseResult.get("result");
                                Log.i(TAG, "run: 支付宝响应数据:" + result);

                                Message msg = new Message();
                                msg.what = SDK_AUTH_FLAG;
                                msg.obj = responseResult;
                                mHandler.sendMessage(msg);
                            }
                        };
                        //启动子线程
                        Thread aliPayAuthThread = new Thread(runnable);
                        aliPayAuthThread.start();
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        view.disMissProgressDialog();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        view.showToast(context.getString(R.string.system_busy));
                        view.setLoginButtonStatus(true);
                    }
                });
    }


    /**
     * 支付宝授权登录
     *
     * @param mapInfo authCode
     */
    private void aliAuthLogin(Map<String, String> mapInfo) {
        Log.i(TAG, "调用服务器端的授权登录接口");
        RetrofitManager.getInstance()
                .createRequest(AliService.class)
                .aliAuthLogin(mapInfo)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        view.disMissProgressDialog();
                        //获取服务器端返回的结果
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            view.disMissProgressDialog();
                            view.setLoginButtonStatus(true);
                            Log.e(TAG, "支付宝授权登录错误" + response.message());
                            view.showToast(context.getString(R.string.system_busy));
                            return;
                        }

                        if (result.isError()) {
                            Log.e(TAG, "支付宝授权登录出错" + result.getMsg());
                            view.disMissProgressDialog();
                            view.setLoginButtonStatus(true);
                            return;
                        }
                        Log.i(TAG, "onResponse:支付宝授权登录成功");
                        analysisResult(result, null);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        Log.e(TAG, "onFailure: " + t.getMessage());
                        view.disMissProgressDialog();
                    }
                });
    }

    private void loginIM(User user, String token) {

        //登录前 initMobileIMSDK ，避免报错203

        // 异步提交登陆id和token
//        new LocalUDPDataSender.SendLoginDataAsync(context, user.getuId(), token) {
//            /**
//             * 登陆信息发送完成后将调用本方法（注意：此处仅是登陆信息发送完成
//             * ，真正的登陆结果要在异步回调中处理哦）。
//             *
//             * @param code 数据发送返回码，0 表示数据成功发出，否则是错误码
//             */
//            @Override
//            protected void fireAfterSendLogin(int code) {
//                view.disMissProgressDialog();
//                if (code == 0) {
//                    Log.i(TAG, "im登陆/连接信息已成功发出！");
//                    view.showLoginSuccess();
//                } else {
//                    view.setLoginButtonStatus(true);
//                    view.showToast(context.getString(R.string.system_busy));
//                    Log.e(TAG, "登陆信息发送失败 code：" + code);
//
//                }
//            }
//        }.execute();
    }


    private String expire(int expireTime) {
        int hours = expireTime / 60;
        int minutes = expireTime % 60;
        return String.format("连续登录错误次数超过限制，还有%d 小时%d分钟后才能重新登录，也可以通过手机号重置密码立即登录", hours, minutes);
    }
}
